package com.yufubao.service.service.applet.elasticsearch.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.yufubao.framework.result.ResponseResult;
import com.yufubao.model.dto.applet.search.SearchDto;
import com.yufubao.service.service.applet.elasticsearch.ESService;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service("esService")
public class ESServiceImpl implements ESService {
    @Autowired
    private RestHighLevelClient client;

    /***
     * applet商户搜索
     * @param searchDto
     * @return
     */
    @Override
    public ResponseResult search(SearchDto searchDto) {
        try {
            SearchRequest request = new SearchRequest();
            //查询
            if (StringUtils.isNotBlank(searchDto.getSearchWords())) {
                request.source().query(QueryBuilders.matchQuery(searchDto.getSearchWords(), "content"));
            }
            //分页
            request.source().from(searchDto.getFromIndex());
            request.source().size(searchDto.getPageSize());
            //排序
            request.source().sort("updateTime", SortOrder.DESC);
            //高亮
            request.source().highlighter(new HighlightBuilder()
                    .field("content").preTags("<em>").postTags("</em>"));
            SearchResponse search = client.search(request, RequestOptions.DEFAULT);
            long value = search.getHits().getTotalHits().value;
            SearchHit[] hits = search.getHits().getHits();
            List<JSONObject> list = new ArrayList<>();
            for (SearchHit hit : hits) {
                String sourceAsString = hit.getSourceAsString();
                JSONObject jsonObject = JSON.parseObject(sourceAsString);
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (highlightFields != null && highlightFields.size() > 0) {
                    String content = highlightFields.get("content").fragments()[0].string();
                    jsonObject.put("h_content", content);
                } else {
                    jsonObject.put("h_content", jsonObject.get("content"));
                }
                list.add(jsonObject);
            }
            return ResponseResult.okResult(list);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
